import { Exchange, getOrderList } from '@/services/chdstore';
import { ExclamationCircleFilled } from '@ant-design/icons';
import {
  ProForm,
  ProFormDigit,
  ProFormGroup,
  ProFormRadio,
} from '@ant-design/pro-components';
import { Button, Form, message, Modal, Progress, Result } from 'antd';
import { round } from 'lodash-es';
import { useRef, useState } from 'react';
import BillingInformation from '../BillingInformation';

export default (props) => {
  const { init, data, add } = props;
  const [form] = Form.useForm();
  const [goodsData, setGoodsData] = useState<{
    goodsName: React.ReactNode;
    goodsNum: number;
    totalPrice: number;
  }>();
  const [step, setStep] = useState(0);
  const [propNum, setPropNum] = useState(0);
  const isBuy = useRef(false);
  const radio1 = Form.useWatch('radio1', form);

  // 关闭后回调
  const afterClose = () => {
    setStep(0);
    setPropNum(0);
    setGoodsData(undefined);
    isBuy.current = false;
  };

  // 关闭
  const onCancel = () => {
    setStep(0);
  };

  // 购买
  const onSave = () => {
    init().then((resData) => {
      const { type, num } = form.getFieldsValue();
      const goodsName = resData.promotionList.find(
        (item) => item.value === radio1,
      )?.label || <span style={{ color: 'red' }}>未选择道具</span>;
      const goodsNum = type === '单次消费' ? 1 : num;
      setGoodsData({
        goodsName,
        goodsNum,
        totalPrice: resData.totalPrice,
      });
      setPropNum(goodsNum);
      setStep(1);
    });
  };

  const send = (number) => {
    return new Promise((res, rej) => {
      setTimeout(async () => {
        const rrrr = await init();

        if (rrrr.shoppingList && rrrr.shoppingList.length === 0) {
          await add();
        }

        const resData = await init();

        if (goodsData.totalPrice !== resData.totalPrice) {
          message.error('消费有误，暂停消费');
          isBuy.current = false;
          return rej();
        }
        await Exchange({
          act: 'exchange',
          radio1,
          // 填1为点卷购买,2为彩虹币购买
          PayId: 2
        });
        const { data } = await getOrderList({
          page: 1,
        });
        if (data[0].orderCode[0] === '-') {
          rej();
        }
        console.log(`Resuest ${number}`);
        res(1);
      }, 1000);
    });
  };

  const onPolling = (current, total) => {
    if (current > total || isBuy.current === false) {
      return;
    }
    send(current).then(() => {
      setPropNum(total - current);
      onPolling(current + 1, goodsData?.goodsNum);
    });
  };

  const fn = () => {
    if (!goodsData) {
      return message.error('系统繁忙');
    }
    isBuy.current = !isBuy.current;
    const current = goodsData.goodsNum - propNum;
    setStep(2);
    onPolling(current + 1, goodsData.goodsNum);
  };

  // 确认购买
  const onBuy = () => {
    if (!data.promotionList.find((item) => item.value === radio1)) {
      Modal.confirm({
        title: '是否确认购买？',
        icon: <ExclamationCircleFilled />,
        content: '未选择消费道具，请确认是否购买',
        onOk() {
          fn();
        },
      });
    } else {
      fn();
    }
  };
  const stepMap: any = {
    1: {
      title: '结算确认',
      mainRender() {
        return (
          <BillingInformation
            init={init}
            data={data}
            type="modal"
            goodsData={goodsData}
          />
        );
      },
      footer: [
        <Button key="close" onClick={onCancel}>
          关闭
        </Button>,
        <Button key="buy" type="primary" onClick={onBuy}>
          确认购买
        </Button>,
      ],
    },
    2: {
      mainRender() {
        if (!goodsData) return null;
        const percent = round(
          ((goodsData?.goodsNum - propNum) / goodsData.goodsNum) * 100,
          1,
        );
        const title =
          propNum === 0
            ? `全部消费完毕，共计${goodsData.goodsNum}次`
            : `批量消费中，剩余次数：${propNum}`;
        const extra = propNum !== 0 && <Button onClick={fn}>暂停/继续</Button>;
        return (
          <Result
            title={title}
            extra={extra}
            icon={
              <Progress
                type="circle"
                percent={percent}
                strokeColor={{
                  '0%': '#87d068',
                  '50%': '#ffe58f',
                  '100%': '#ffccc7',
                }}
              />
            }
          />
        );
      },
      footer: [],
    },
  };

  return (
    <>
      <ProForm
        form={form}
        submitter={{
          render(props, doms) {
            return [
              doms[0],
              <Button key="buy" type="primary" onClick={onSave}>
                购买
              </Button>,
            ];
          },
        }}
      >
        <ProFormGroup>
          <ProFormRadio.Group
            name="radio1"
            // label="促销活动"
            layout="vertical"
            options={data.promotionList}
            rules={[
              {
                required: true,
              },
            ]}
          />
        </ProFormGroup>
        <ProFormRadio.Group
          name="type"
          label="消费类型"
          initialValue={'单次消费'}
          options={['单次消费', '批量消费']}
        />
        {
          <Form.Item shouldUpdate noStyle>
            {(form) => {
              if (form.getFieldValue('type') !== '批量消费') {
                return null;
              }
              return (
                <ProFormDigit
                  width="md"
                  name="num"
                  label="消费次数"
                  initialValue={1}
                  min={1}
                  fieldProps={{
                    precision: 0,
                  }}
                />
              );
            }}
          </Form.Item>
        }
      </ProForm>
      <Modal
        title={stepMap[step]?.title}
        open={step > 0}
        width={700}
        footer={stepMap[step]?.footer}
        afterClose={afterClose}
        onCancel={onCancel}
      >
        {stepMap[step]?.mainRender()}
      </Modal>
    </>
  );
};
